package git

import (
	"github.com/chmodke/gitmm/config"
	"github.com/chmodke/gitmm/log"
	"github.com/chmodke/gitmm/util"
	"io/ioutil"
	"path/filepath"
	"strings"
)

func Command(workDir string, repo config.Repo, args []string) bool {
	builder := &util.CmdBuilder{}
	builder.Add("git")
	for _, arg := range args {
		builder.Add(arg)
	}
	out, ret := util.GetOut(util.Execute(repo.LocalPath(workDir), builder.Build()))
	log.Consoleln(out)
	return ret
}

func FindGit(dirPth string) (files []string, err error) {
	files = make([]string, 0, 10)

	dir, err := ioutil.ReadDir(dirPth)
	if err != nil {
		return nil, err
	}

	for _, fi := range dir {
		if !fi.IsDir() {
			continue
		}
		if isGit(filepath.Join(dirPth, fi.Name())) {
			files = append(files, fi.Name())
		}
	}
	return files, nil
}

func isGit(dirPth string) bool {
	dir, err := ioutil.ReadDir(dirPth)
	if err != nil {
		return false
	}
	for _, fi := range dir {
		if !fi.IsDir() {
			continue
		}
		if strings.EqualFold(".git", fi.Name()) {
			return true
		}
	}
	return false
}
